﻿using CodeParser.Tokens;

namespace CodeParser.Expressions
{
    public class TechniqueParser
        : ExpressionParser
    {

        public override Expression Parse(Token[] tokens, int index)
        {
            var firstToken = tokens[index];
            if (firstToken.Type == TokenType.Identifier && firstToken.Value.StartsWith("technique"))
            {
                var expression = new Technique {TechniqueToken = firstToken, StringIndex = firstToken.Index};
                expression.Add(new SingleToken() { Token = firstToken});
                if (index < tokens.Length - 1 && tokens[index + 1].Type == TokenType.Identifier)
                {
                    expression.Identifier = tokens[index + 1];
                    expression.Add(new SingleToken() { Token = expression.Identifier });
                    expression.TokenLength = 2;

                    if (index < tokens.Length - 2 && tokens[index + 2].Value == "<")
                    {
                        expression.Annotation = AnnotationParser.Parse(tokens, index + 2);
                        if (expression.Annotation != null)
                        {
                            expression.TokenLength = 2 + expression.Annotation.TokenLength;
                            expression.Add(expression.Annotation);
                        }
                    }

                    var codeBlockIndex = ParseUtils.FindTokenIndex(tokens, index + 2, TokenType.CurlyOpen);
                    if (codeBlockIndex.HasValue)
                    {
                        expression.CodeBlock = CodeBlockParser.Parse(tokens, codeBlockIndex.Value);
                        if (expression.CodeBlock != null)
                        {
                            expression.TokenLength = codeBlockIndex.Value - index + expression.CodeBlock.TokenLength;
                            expression.Add(expression.CodeBlock);
                        }
                    }

                    var lastToken = tokens[index + expression.TokenLength - 1];
                    expression.StringLength = lastToken.Index + lastToken.Value.Length - expression.StringIndex;

                    return expression;
                }
            }
            return null;
        }

        public ExpressionParser CodeBlockParser { get; set; }

        public ExpressionParser AnnotationParser { get; set; }

    }
}
